/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.agilelang.editor.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import javax.swing.JOptionPane;
import org.agilelang.config.AgileConfig;
import org.agilelang.config.AgileStructure;
import org.agilelang.config.AgileSyntax;
import org.agilelang.config.FileStatic;
import org.agilelang.config.ReadConfig;
import org.agilelang.config.ScannerConfig;
import org.agilelang.editor.ViewFrame;
import org.agilelang.generate.AgileGenerator;
import org.agilelang.generate.UtilFile;
import org.agilelang.scanner.Scanner;
//import org.agilelang.generator.cakephp.DlgGenerateCakePHP;
//import org.agilelang.generator.cakephp.ICakePHP;

public class Generate implements ActionListener {

    ViewFrame frame;

    public Generate(ViewFrame frame) {
        this.frame = frame;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        frame.save();
        String path = frame.getPathProject();

        String folder_tmp = "tmp";
        String folder_static = "static";
        String folder_tmpl = "tmpl";
        String folder_source = "source";
        String folder_config = "config";

        File tmp = new File(path + File.separator + folder_tmp);
        if (!tmp.exists()) {
            if (tmp.mkdir()) {
                System.out.println("Directorio temporal creado : " + path + File.separator + folder_tmp);
            } else {
                System.err.println("Error no se puede crear directorio temporal");
            }
        } else {
            System.out.println("Directorio temporal ya existe : " + path + File.separator + folder_tmp);
        }

        tmp = new File(path + File.separator + folder_static);
        if (!tmp.exists()) {
            if (tmp.mkdir()) {
                System.out.println("Directorio statico creado : " + path + File.separator + folder_static);
            } else {
                System.err.println("Error no se puede crear directorio statico");
            }
        } else {
            System.out.println("Directorio statico ya existe : " + path + File.separator + folder_static);
        }
        //----------------------------------------------------------------------

        File file_config = new File(path + File.separator + folder_config);
        String lineFromFile_config = "";
        for (File file : file_config.listFiles()) {
            System.out.println("Generate : " + file.getAbsolutePath());
            Path newFile = Paths.get(file.getAbsolutePath());
            try (BufferedReader reader = Files.newBufferedReader(
                    newFile, Charset.defaultCharset())) {
                String lineFromFile = "";
                System.out.println("The contents of file are: ");
                while ((lineFromFile = reader.readLine()) != null) {
                    System.out.println(lineFromFile);
                    lineFromFile_config += lineFromFile;
                }

            } catch (IOException exception) {
                System.out.println("Error while reading file");
            }
        }

        //Create a new Path
        Path newFile = Paths.get(path + File.separator + folder_config + File.separator + "out_config");
        try {
            Files.deleteIfExists(newFile);
            newFile = Files.createFile(newFile);
        } catch (IOException ex) {
            System.out.println("Error creating file");
        }
        System.out.println(Files.exists(newFile));
        //Writing to file4
        try (BufferedWriter writer = Files.newBufferedWriter(
                newFile, Charset.defaultCharset())) {
            writer.append(lineFromFile_config);

            writer.flush();
        } catch (IOException exception) {
            System.out.println("Error writing to file");
        }

        ScannerConfig scanner_config = new ScannerConfig(path + File.separator + folder_config + File.separator + "out_config",
                path + File.separator + folder_tmp + File.separator + "config_out.xml");

        //----------------------------------------------------------------------
        ReadConfig read_config = new ReadConfig();
        read_config.process(path + File.separator + folder_tmp + File.separator + "config_out.xml");
        AgileConfig aconfig = read_config.getAconfig();
        AgileStructure astructure = read_config.getAstructure();
        HashMap<String, AgileSyntax> hashAgileSyntax = read_config.getHashAgileSyntax();
        //----------------------------------------------------------------------
        //----------------------------------------------------------------------
        List<String> folders = astructure.folder;
        for (String folder : folders) {
            File file_folder = new File(aconfig.folderOut + File.separator + folder);
            if (!file_folder.exists()) {
                if (file_folder.mkdir()) {
                    System.out.println("Directorio creado : " + file_folder.getAbsolutePath());
                } else {
                    System.err.println("Error no se puede crear directorio : " + file_folder.getAbsolutePath());
                }
            } else {
                System.out.println("Directorio ya existe : " + file_folder.getAbsolutePath());
            }
        }
        //----------------------------------------------------------------------
        List<FileStatic> files = astructure.file;
        for (FileStatic archive : files) {
            File file_archive = new File(path + File.separator + folder_static + File.separator + archive.input);
            if (file_archive.exists()) {
                String content = UtilFile.readFile(path + File.separator + folder_static + File.separator + archive.input);
                UtilFile.writefile(aconfig.folderOut + File.separator + archive.output, content);
                System.out.println("Copiar archivo : " + aconfig.folderOut + File.separator + archive.output);
            } else {
                System.err.println("No se encuentra archivo  : " + path + File.separator + folder_static + File.separator + archive.input);
            }
        }
        //----------------------------------------------------------------------
        File file_source = new File(path + File.separator + folder_source);
        String lineFromFile_source = "";
        for (File file : file_source.listFiles()) {
            System.out.println("Generate : " + file.getAbsolutePath());
            Path newFile1 = Paths.get(file.getAbsolutePath());
            try (BufferedReader reader = Files.newBufferedReader(
                    newFile1, Charset.defaultCharset())) {
                String lineFromFile = "";
                System.out.println("The contents of file are: ");
                while ((lineFromFile = reader.readLine()) != null) {
                    System.out.println(lineFromFile);
                    lineFromFile_source += lineFromFile;
                }

            } catch (IOException exception) {
                System.out.println("Error while reading file");
            }
        }

        //Create a new Path
        Path newFile1 = Paths.get(path + File.separator + folder_source + File.separator + "out_source");
        try {
            Files.deleteIfExists(newFile1);
            newFile = Files.createFile(newFile1);
        } catch (IOException ex) {
            System.out.println("Error creating file");
        }
        System.out.println(Files.exists(newFile1));
        //Writing to file4
        try (BufferedWriter writer = Files.newBufferedWriter(
                newFile1, Charset.defaultCharset())) {
            writer.append(lineFromFile_source);

            writer.flush();
        } catch (IOException exception) {
            System.out.println("Error writing to file");
        }

        Scanner scanner = new Scanner(path + File.separator + folder_source + File.separator + "out_source", 
                read_config.getListObjectClass(), path + File.separator + folder_tmp + File.separator + "scanner_out.xml");
        //----------------------------------------------------------------------
        AgileGenerator ag = new AgileGenerator();
        ag.process(path + File.separator + folder_tmp + File.separator + "scanner_out.xml",
                path + File.separator + aconfig.folderTemplate, 
                aconfig.folderOut, read_config.getListObjectClass());

    }

}
